package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by yuanxin
 * Date:2019/7/3
 * Time:11:42
 */
@RestController
@RequestMapping("/item")
public class ItemController {
    @Reference
    private SpuService spuService;
    @Reference
    private CategoryService categoryService;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${pagePath}")
    private String pagePath;

    /**
     * 创建sku页面
     *
     * @param id
     */
    @GetMapping("/createPage")
    public void createPage(String id) {
        //查询商品信息
        Goods goods = spuService.findGoodsById(id);
        //获取SPU 信息
        Spu spu = goods.getSpu();
        //获取sku列表
        List<Sku> skuList = goods.getSkuList();
        //查询商品分类
        ArrayList<String> categoryList = new ArrayList<>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());

        //
        Map<String, String> urlMap = new HashMap<>();
        for (Sku sku : skuList) {
            if ("1".equals(sku.getStatus())) {
                String specJSON = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJSON,sku.getId()+".html");
            }
        }

        //创建页面（每个SKU为一个页面）
        for (Sku sku : skuList) {
            // 1.上下文
            Context context = new Context();
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("spu",spu);
            dataModel.put("sku",sku);
            dataModel.put("categoryList",categoryList);
            dataModel.put("skuImages",sku.getImages().split(","));//sku图片
            dataModel.put("spuImages",spu.getImages().split(","));//spu图片
            Map paraIrems = JSON.parseObject(spu.getParaItems());
            Map specItems = JSON.parseObject(sku.getSpec());
            dataModel.put("paraIrems",paraIrems);
            dataModel.put("specItems",specItems);
            //规格选择面板
            Map<String,List> specMap = (Map) JSON.parse(spu.getSpecItems());

            for (String key : specMap.keySet()) {
                List<String> list = specMap.get(key);
                List<Map> specList = new ArrayList<>();
                for (String value : list) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("option",value);
                    if (value.equals(specItems.get(key))) {
                        map.put("checked",true);
                    }else {
                        map.put("checked",false);
                    }
                    //对规格json字符串进行排序
                    Map spec = JSON.parseObject(sku.getSpec()); //{颜色:红色   ,尺码 :32}
                    spec.put(key,value);//{颜色:白色,尺码 :32}
                    String specJSON = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    map.put("url",urlMap.get(specJSON));
                    specList.add(map);
                }
                specMap.put(key,specList);//用新集合覆盖原集合
            }
            dataModel.put("specMap",specMap);//规格面板
            context.setVariables(dataModel);
            //生成目录
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId() + ".html");
            System.out.println("生成"+dest.getName());
            //创建页面（每个SKU为一个页面）
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item",context,writer);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

    }

}
